// chat-ui/src/store/user.js
import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { ref, reactive } from 'vue'

import defaultAvatar from '@/assets/images/profile.jpg'

// 创建响应式状态
const token = ref(getToken())
const userId = ref('')
const userName = ref('')
const nickname = ref('')
const phone = ref('')
const email = ref('')
const avatar = ref('')
const roles = reactive([])
const permissions = reactive([])
const userInfo = reactive({})

// 用户状态管理
export default {
    // 获取状态
    getToken: () => token.value,
    getUserId: () => userId.value,
    getUserName: () => userName.value,
    getNickname: () => nickname.value,
    getAvatar: () => avatar.value,
    getPhone: () => phone.value,
    getEmail: () => email.value,
    getRoles: () => roles,
    getPermissions: () => permissions,
    getUserInfo: () => userInfo,

    // 设置状态
    setToken: (value) => {
        token.value = value
        setToken(value)
    },
    setUserId: (value) => {
        userId.value = value
    },
    setUserName: (value) => {
        userName.value = value
    },
    setNickname: (value) => {
        nickname.value = value
    },
    setAvatar: (value) => {
        avatar.value = value
    },
    setPhone: (value) => {
        phone.value = value
    },
    setEmail: (value) => {
        email.value = value
    },
    setRoles: (values) => {
        roles.length = 0
        roles.push(...values)
    },
    setPermissions: (values) => {
        permissions.length = 0
        permissions.push(...values)
    },
    setUserInfo: (info) => {
        Object.assign(userInfo, info)
    },

    // 清除状态
    clearState: () => {
        token.value = ''
        userId.value = ''
        userName.value = ''
        nickname.value = ''
        avatar.value = ''
        email.value = ''
        phone.value = ''
        roles.length = 0
        permissions.length = 0
        Object.keys(userInfo).forEach(key => {
            delete userInfo[key]
        })
        removeToken()
    },

    // 登录操作
    login: (userInfo) => {
        const { username, password, code, uuid } = userInfo
        return new Promise((resolve, reject) => {
            login(username, password, code, uuid)
                .then(res => {
                    if (res.code === 200) {
                        // 设置token
                        token.value = res.token
                        setToken(res.token)
                        resolve(res)
                    } else {
                        reject(res.msg || '登录失败')
                    }
                })
                .catch(error => {
                    reject(error)
                })
        })
    },

    // 退出登录
    logout: () => {
        return new Promise((resolve, reject) => {
            logout()
                .then(() => {
                    // 清除用户状态
                    token.value = ''
                    userId.value = ''
                    userName.value = ''
                    nickname.value = ''
                    email.value = ''
                    phone.value = ''
                    avatar.value = ''
                    roles.length = 0
                    permissions.length = 0
                    Object.keys(userInfo).forEach(key => {
                        delete userInfo[key]
                    })
                    removeToken()
                    resolve()
                })
                .catch(error => {
                    reject(error)
                })
        })
    },

    // 获取用户信息
    getInfo: () => {
        return new Promise((resolve, reject) => {
            getInfo()
                .then(res => {
                    if (res.code === 200) {
                        const { user, roles: roleList, permissions: permissionList } = res

                        // 设置用户信息
                        userId.value = user.userId
                        userName.value = user.userName
                        nickname.value = user.nickName || ''
                        email.value = user.email
                        phone.value = user.phonenumber
                        // 处理头像路径
                        if (user.avatar) {
                            // 如果头像不是完整URL，添加基础路径
                            if (!/^(http|https):\/\//.test(user.avatar)) {
                                avatar.value = process.env.VUE_APP_BASE_API + user.avatar
                            } else {
                                avatar.value = user.avatar
                            }
                        } else {
                            // 设置默认头像
                            avatar.value = defaultAvatar;                 }

                        // 设置角色和权限
                        if (roleList && roleList.length > 0) {
                            roles.length = 0
                            roles.push(...roleList)
                        } else {
                            roles.length = 0
                            roles.push('ROLE_DEFAULT')
                        }

                        if (permissionList && permissionList.length > 0) {
                            permissions.length = 0
                            permissions.push(...permissionList)
                        }

                        // 保存完整的用户信息
                        Object.assign(userInfo, user)

                        resolve(res)
                    } else {
                        reject(res.msg || '获取用户信息失败')
                    }
                })
                .catch(error => {
                    reject(error)
                })
        })
    },

    // 检查是否有特定权限
    hasPermission: (permission) => {
        return permissions.includes(permission)
    },

    // 检查是否有特定角色
    hasRole: (role) => {
        return roles.includes(role)
    }
}